package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.DevicePropertiesVo;
import com.zzyl.nursing.dto.PageDeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-26
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //华为云物联网平台
    @Autowired
    private IoTDAClient client;

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis
        redisTemplate.opsForValue().set("products", JSONUtil.toJsonStr(response.getProducts()));

    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }


    @Override
    public List<ProductVo> getProductList() {
        //从redis中查询数据
        String jsonStr = redisTemplate.opsForValue().get("products");
        //如果数据为空，则返回一个空集合
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        //解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Transactional
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1. 设备标识不能重复
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId());
        Device device = super.getOne(wrapper);
        if (device != null) {
            throw new BaseException("设备名称或者标识码重复");
        }
        //2. 同一个位置不能重复绑定设备(位置重复，设备重复)
        LambdaQueryWrapper<Device> queryWrapper = Wrappers.<Device>lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType());
        device = super.getOne(queryWrapper);
        if (device != null) {
            throw new BaseException("设备位置重复");
        }
        //3. 去华为注册
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setNodeId(deviceDto.getNodeId());
        addDevice.setProductId(deviceDto.getProductKey());
        addDevice.setDeviceId(deviceDto.getIotId());
        addDevice.setDeviceName(deviceDto.getDeviceName());
        addDeviceRequest.setBody(addDevice);

        AddDeviceResponse response = client.addDevice(addDeviceRequest);
        //4. 本地保存到device
        Device deviceLocal = new Device();
        BeanUtils.copyProperties(deviceDto, deviceLocal);
        deviceLocal.setIotId(response.getDeviceId());
        deviceLocal.setSecret(response.getAuthInfo().getSecret());
        super.save(deviceLocal);
    }

    /**
     * 设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo deviceDetail(String iotId) {
        DeviceDetailVo detailVo = new DeviceDetailVo();
        //从数据库查询大部分信息
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (device == null) {
            new RuntimeException("设备不存在");
        }
        BeanUtils.copyProperties(device, detailVo);
        //从华为云查询小部分信息
        ShowDeviceRequest deviceRequest = new ShowDeviceRequest();
        deviceRequest.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(deviceRequest);
        detailVo.setDeviceStatus(response.getStatus());
        //激活时间
        String activeTimeStr = response.getActiveTime();
        //注意：有可能没有激活
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC)).
                    withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();

            detailVo.setActiveTime(activeTime);
        }
        return detailVo;
    }

    /**
     * 监测数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DevicePropertiesVo> queryDeviceServiceProperties(String iotId) {
        // 所有的监测数据都是在华为云上面，所以需要在华为云上面去取数据
        ShowDeviceShadowRequest shadowRequest = new ShowDeviceShadowRequest();
        shadowRequest.setDeviceId(iotId);
        ShowDeviceShadowResponse shadowResponse = client.showDeviceShadow(shadowRequest);
        log.info("查询设备属性成功:", shadowResponse);

        // 获取属性
        Object properties = shadowResponse.getShadow().get(0).getReported().getProperties();
        // 获取时间
        String eventTimeStr = shadowResponse.getShadow().get(0).getReported().getEventTime();

        LocalDateTime evenTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyMMdd'T'HHmmss'Z'");
        evenTime = evenTime.atZone(ZoneId.from(ZoneOffset.UTC)).
                withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();

        if (properties == null) {
            new RuntimeException("属性为空");
        }
        // 转为JSONObject
        JSONObject propertiesJson = JSONUtil.parseObj(properties);
        // 创建返回的集合
        ArrayList<DevicePropertiesVo> propertiesVos = new ArrayList<>();
        // 将属性给返回的对象赋值，然后将对象加入集合里面
        LocalDateTime finalEvenTime = evenTime;
        propertiesJson.forEach((key, value) -> {
            DevicePropertiesVo propertiesVo = new DevicePropertiesVo();
            propertiesVo.setFunctionId(key);
            propertiesVo.setValue(value.toString());
            propertiesVo.setEventTime(finalEvenTime);
            propertiesVos.add(propertiesVo);
        });

        return propertiesVos;
    }

    /**
     * 删除华为云上面的设备
     *
     * @param iotId
     */
    @Override
    public void deleteDevice(String iotId) {
        // 1. 先根据设备的iotId在华为云查询设备
        //    存在的话，则删除设备  不存在则抛出异常
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        client.deleteDevice(request);
        // 2. 华为云上面不存在也要去查询数据库中的设备 有则删除，没有则不管
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId);
        long count = super.count(wrapper);
        if (count > 0) {
            super.remove(wrapper);
        }
    }

}
